# coding=utf-8
import re
import pandas as pd
import os
from optparse import OptionParser
import random
import shutil
from getMp3 import getMP3
from ps import PlaySound
import threading


def playWord(word):
    getMP3(word)
    t = threading.Thread(target=PlaySound, args=(word,))
    t.start()


def resetWeight(data, filename):
    shutil.copyfile(filename, filename + '.bak')
    for i in range(0, len(data)):
        data.loc[i, '权重'] = 0  # 重置权重
    data.to_excel(filename, index=False)


def randTimes(data, weight):
    if weight.__eq__("F"):
        random.shuffle(cList)
    else:
        for i in range(0, len(data)):
            if int(data['权重'][i]) > 0:
                num = 5 if 5 < int(data['权重'][i]) else int(data['权重'][i])
                for j in range(0, num):
                    cList.append(data['翻译'][i])
        random.shuffle(cList)


def randTimes2(data, weight):
    if weight.__eq__("F"):
        random.shuffle(eList)
    else:
        for i in range(0, len(data)):
            if int(data['权重'][i]) > 0:
                num = 5 if 5 < int(data['权重'][i]) else int(data['权重'][i])
                for j in range(0, num):
                    eList.append(data['词汇'][i])
        random.shuffle(eList)


def removeWord(word, weight):
    if weight.__eq__("F"):
        cList.remove(word)
    else:
        for item in cList[:]:
            if item == word:
                cList.remove(word)


def removeWord2(word, weight):
    if weight.__eq__("F"):
        eList.remove(word)
    else:
        for item in eList[:]:
            if item == word:
                eList.remove(word)


def addWeight(data, filename):
    # print(wList)
    # print(tempList)
    for i in wList:
        # print(tempList.index(i)+2)
        id = tempList.index(i)
        if data.loc[id, '权重'] < 5:
            data.loc[id, '权重'] += 1  # 增加权重
    for i in wList2:
        # print(tempList.index(i)+2)
        id = tempList.index(i)
        if data.loc[id, '权重'] > 0:
            data.loc[id, '权重'] -= 1  # 减少权重
    data.to_excel(filename, index=False)


def c2e(data, times, weight, aw, filename):  # 汉译英
    input("按下回车开始汉译英默写: [Enter]")
    randTimes(data, weight)
    reList.append(times)
    reList.append(0)
    for i in range(0, times):
        word = cList[0]
        print(str(i + 1) + ".翻译: " + word)
        playWord(dataDic2[word])
        myWord = input("单词: ")
        if (myWord in dataDic1) and (dataDic1[myWord].__eq__(word)):
            print('正确√！' + dataDicString[myWord] + "\n")
            if aw.__eq__('T'):
                wList2.append(dataDic2[word])
        else:
            print('错误×！正确答案: ' + dataDic2[word] + " " + dataDicString[dataDic2[word]] + "\n")
            reList[1] += 1
            if aw.__eq__('T'):
                wList.append(dataDic2[word])
        removeWord(word, weight)
    percent = round(((reList[0] - reList[1]) / reList[0]), 2) * 100
    print("默写结束！ 总共词数:" + str(reList[0]) + ", 错误词数:" + str(reList[1]) + ",正确率:" + str(percent) + "%")
    if aw.__eq__('T'):
        shutil.copyfile(filename, filename + '.bak')
        addWeight(data, filename)


def e2c(data, times, weight, aw):  # 英译汉
    input("按下回车开始英译汉默写: [Enter]")
    randTimes2(data, weight)
    reList.append(times)
    reList.append(0)
    for i in range(0, times):
        word = eList[0]
        print(str(i + 1) + ".词汇: " + word)
        myWord = input("翻译: ")
        searchList = re.findall(myWord, dataDic1[word])
        if (len(searchList) > 0) and (myWord != ""):
            print('正确√！完整翻译: ' + dataDic1[word] + " " + dataDicString[word] + "\n")
        else:
            print('错误×！正确答案: ' + dataDic1[word] + " " + dataDicString[word] + "\n")
            reList[1] += 1
        removeWord2(word, weight)
    percent = round(((reList[0] - reList[1]) / reList[0]), 2) * 100
    print("默写结束！ 总共词数:" + str(reList[0]) + ", 错误词数:" + str(reList[1]) + ",正确率:" + str(percent) + "%")


def getLine(data, lines):
    # print(lines)
    # 130,140 取130行到140行
    if re.match(r'^\d.+,\d.+$', lines) is not None:
        lineList = lines.split(',')
        lineList = [int(x) - 2 for x in lineList]
        lineRange = range(int(lineList[0]), int(lineList[1]) + 1)
        data = data.loc[list(lineRange)]
        return data
    # 10 取前10行
    if re.match(r'^\d.*$', lines) is not None:
        lineRange = range(int(lines))
        data = data.loc[lineRange]
        return data
    # -10 取倒数10行
    if re.match(r'^-\d.*$', lines) is not None:
        lines = lines.strip("-")
        lineRange = range(len(data) - int(lines), len(data))
        data = data.loc[lineRange]
        return data


def readFile(data):  # 读取dataFrame内容
    for i, row in data.iterrows():  # 遍历dataFrane
        dataDic1[data['词汇'][i]] = data['翻译'][i]
        dataDic2[data['翻译'][i]] = data['词汇'][i]
        dataDicString[data['词汇'][i]] = "[过去式: " + data['过去式'][i] + ", 过去分词: " + data['过去分词'][i] + ", 现在分词: " + \
                                       data['现在分词'][i] + "]"
        eList.append(data['词汇'][i])
        cList.append(data['翻译'][i])
    for j in eList:
        tempList.append(j)


def run():
    parser = OptionParser("-f <filePayload> -t <writeType[c2e]> -n <writeTimes> -w <weight[false]>")
    parser.add_option("-f", "--filename", type="string", dest="filename", default="engWords.xlsx",
                      help="指定excel文件路径，默认为engWords")
    parser.add_option("-t", "--type", type="string", dest="writeType", default="c2e",
                      help="选择默写类型为英译汉(e2c)或汉译英(c2e)，默认为汉译英(c2e)")
    parser.add_option("-n", "--times", type="int", dest="times", default=-1, help="选择本次默写单词数量, 0为全部默写")
    parser.add_option("-l", "--lines", type="string", dest="lines", default=-1, help="指定行数范围进行默写")
    parser.add_option("-o", "--ow", type="int", dest="onlyWeight", default=0, help="只选择大于某权重值的单词进行默写")
    parser.add_option("-w", "--weight", type="string", dest="weight", default="F",
                      help="T:按照权重增加单词出现率, F:不按照权重默写单词 权重上限为5")
    parser.add_option("-a", "--addWeight", type="string", dest="addWeight", default="F",
                      help="T:写错时增加该单词权重,写对时减少, F:写错时不增加该单词权重 权重上限为5")
    parser.add_option("-r", "--reset", type="string", dest="resetWeight", default="F",
                      help="T:重置权重即全部清0, F:默认不重置权重")
    (options, args) = parser.parse_args()
    if (options.times == -1) and (options.resetWeight != 'T'):
        print(parser.usage)
        os._exit(0)
    try:
        data = pd.read_excel(options.filename)  # 从指定xlsx读取单词DataFrame
        if options.lines != -1:
            if(len(data) < int(options.lines)):
                options.lines = len(data)            
            data = getLine(data, options.lines)
            options.weight = "F"  # 不能和Weight模式同时使用！
            options.addWeight = "F"
        if options.onlyWeight is not None and options.onlyWeight > 0:
            data = data.loc[data['权重'] >= int(options.onlyWeight)]  # 筛选出大于某权重的所有单词
            options.weight = "F"  # onlyWeight不能和Weight模式同时使用！
            options.addWeight = "F"
        if options.times > len(data) or options.times == 0:
            options.times = len(data)
        readFile(data)
        # print(dataDic)
        # print(eList)
        if options.resetWeight.__eq__('T'):
            boolean = input("是否确定重置权重? (T/F)")
            if boolean.__eq__('T'):
                resetWeight(data, options.filename)
            os._exit(0)
        if options.writeType.__eq__("c2e"):
            c2e(data, options.times, options.weight, options.addWeight, options.filename)
        else:
            e2c(data, options.times, options.weight, options.addWeight)
    except Exception as e:
        print(e)
        # pass

if __name__ == '__main__':
    cList = []  # 翻译列表
    eList = []  # 单词列表
    wList = []  # 权重增加列表
    wList2 = []  # 权重减少列表
    reList = []  # 结果统计列表
    tempList = []  # 备份列表
    dataDic1 = {}  # 英译汉字典
    dataDic2 = {}  # 汉译英字典
    dataDicString = {}  # 分词词典
    print("""
    ###########################################################################################
    #  Wordzzz单词默写工具1.2                                                             #
    #  by: FlayerVEO                                                                      #
    #  例1: python3 Wordzzz.py -r T   --重置权重                                          #
    #  例2: python3 Wordzzz.py -t c2e -n 3 -w T  --汉译英方式默写3个单词,开启权重模式     #
    #  例3: python3 Wordzzz.py -t e2c -n 10  --英译汉方式写出10个单词的词义               #
    #  例4: python3 Wordzzz.py -t c2e -n 3 -w T -a T --启用权重模式且权重变化默写3个单词  #
    #  例5: python3 Wordzzz.py -t c2e -n 0 -l 130,140 --默写130行到140行的单词            #       
    #  例5: python3 Wordzzz.py -t c2e -n 0 -o 1 --默写所有权重大于1的单词                 #    
    ###########################################################################################""")
    run()
